/*
    Copyright (c) Guangzhou Data Control Network Technology Co., Ltd. All rights reserved.
    Licensed under the MIT License.
    contact:dcdev_founder@foxmail.com
*/
function _dc_ui_on_input_validate_(type) {
    var data = window["_dc_ui_inputor_data_"];
    if (data.max_value) {
        var text_length = $(`#_dc_ui_inputor_${data.type}_input_`).val().length;
        // 不符合
        if (text_length < data.min_value || text_length > (parseInt(data.max_value) - 1)) {
            if (text_length == parseInt(data.max_value)) {
                $(`#_dc_ui_inputor_confirm_`).attr("disabled", false);
                $(`#_dc_ui_inputor_tips_`).html(`${text_length} / ${data.max_value}`).css("color", "black");
            }
            else {
                $(`#_dc_ui_inputor_confirm_`).attr("disabled", true);
                $(`#_dc_ui_inputor_tips_`).html(`${text_length} / ${data.max_value}`).css("color", "gray");
            }
        }
        // 符合
        else {
            $(`#_dc_ui_inputor_confirm_`).attr("disabled", false);
            $(`#_dc_ui_inputor_tips_`).html(`${text_length} / ${data.max_value}`).css("color", "black");
        }
    }
}

function _dc_ui_block_div_events_(id) {
    const canScrollEl = ($el, up) => {
        const overflow = up ?
            Math.abs($el.scrollTop) > Number.EPSILON :
            $el.scrollHeight - $el.scrollTop - $el.clientHeight > Number.EPSILON;
        if (!overflow) {
            return false;
        }
        const styles = getComputedStyle($el);
        if (styles['overflow-y'] !== 'auto' && styles['overflow-y'] !== 'scroll') {
            return false;
        }
        return true;
    };

    const canScrollEls = ($child, $root, up) => {
        let $el = $child;
        while ($el) {
            if (canScrollEl($el, up)) {
                return true;
            }
            if ($el === $root) {
                break;
            }
            $el = $el.parentNode;
        }
        return false;
    };

    const preventEvent = (e) => {
        e.preventDefault();
        e.stopPropagation();
        e.returnValue = false;
        return false;
    };

    const eventData = {
        touchesPos: {},
        moving: false,
        canScroll: false,
    };

    const el = document.getElementById(id);
    if (el == null) {
        console.error(`id 为 ${id} 的div不存在.`);
    }
    else {
        el.addEventListener('scroll', (e) => {
            return preventEvent(e);
        }, {
            capture: true,
            passive: false,
            once: false
        });

        el.addEventListener('onscroll', (e) => {
            return preventEvent(e);
        }, {
            capture: true,
            passive: false,
            once: false
        });

        el.addEventListener('mousewheel', (e) => {
            if (canScrollEls(e.target, el, e.wheelDelta > 0)) {
                return void 0;
            }
            return preventEvent(e);
        }, {
            capture: true,
            passive: false,
            once: false
        });

        el.addEventListener('touchstart', (e) => {
            // record touch start pos
            Object.keys(e.changedTouches).forEach((i) => {
                const touch = e.changedTouches[i];
                eventData.touchesPos[touch.identifier] = {
                    startY: touch.clientY,
                    currentY: touch.clientY,
                };
            });
            eventData.moving = false;
            eventData.canScroll = false;

            e.stopPropagation();
            e.preventDefault();

        }, {
            capture: true,
            passive: false,
            once: false
        });

        el.addEventListener('touchmove', (e) => {
            // update current touch pos and calc touches sum delta distance
            let touchDeltaY = 0;
            Object.keys(e.changedTouches).forEach((i) => {
                const touch = e.changedTouches[i];
                const cache = eventData.touchesPos[touch.identifier];
                if (cache) {
                    touchDeltaY += touch.clientY - cache.currentY;
                    cache.currentY = touch.clientY;
                }
            });
            const canScroll = canScrollEls(e.target, el, touchDeltaY > 0);
            if (!eventData
                .moving
            ) { // if first move cannot scroll this layer, all move after will not scroll this layer
                eventData.moving = true;
                eventData.canScroll = canScroll;
            }
            if (canScroll && eventData.canScroll) {
                return void 0;
            }
            return preventEvent(e);
        }, {
            capture: true,
            passive: false,
            once: false
        });

        el.addEventListener('touchend', (e) => {
            if (e && e.touches && e.touches.length !== 0) {
                return;
            }
            eventData.touchesPos = {};
        }, {
            capture: true,
            passive: false,
            once: false
        });
    }
}

(function (window, undefined) {
    // 执行xhr时是否自动显示loading
    xhr_show_loading = document.getElementById("ui_class") ? document.getElementById("ui_class").getAttribute("xhr_show_loading") : true;
    if (xhr_show_loading === "false" || xhr_show_loading === "0")
        xhr_show_loading = false;
    if (xhr_show_loading) {
        $.ajaxSetup({
            //发送请求前触发
            beforeSend: function (xhr) {
                if (ui_class)
                    ui_class.show_loading();
            },
            //完成请求后触发(success或error后)
            complete: function (xhr, status) {
                if (ui_class)
                    ui_class.hide_loading();
                if (xhr.status != 200) {

                }
            }
        })
    }
    // 插入css+html
    var style = document.createElement(`style`);
    style.type = `text/css`;
    style.className = "_dcdev_preset_";
    style.innerHTML = `@keyframes rotate {0% {}100% {transform: rotate(360deg);}}`;
    document.getElementsByTagName(`HEAD`).item(0).appendChild(style);

    var left = (browser_info.width / 2) - 14;
    var top = (browser_info.height / 2) - 14;
    var max_width = browser_info.width >= 320 ? 280 : browser_info.width - 100;
    {
        var html = `
<div id="_dc_ui_mask_" class="_dcdev_preset_" style="z-index:99999;position:fixed;top:0;left:0;width:100%;height:100%;background-color:black;opacity:0;display:none;"></div>
<div id="_dc_ui_loading_container_" class="_dcdev_preset_" style="position:absolute;top:0px;left:0px;z-index:999999;display:none;">
    <div style="position:absolute;top:${top}px;left:${left}px;">
        <img style="width:28px;height:28px;animation: 2s rotate linear infinite;" src="https://res.dcdev.net/dcdev/v1.0.6/assets/images/loading.svg" />
    </div>
</div>
<div id="_dc_ui_container_" class="_dcdev_preset_" style="position:absolute;top:0px;left:0px;z-index:999999;display:none;">
    <div id="_dc_ui_container__" style="padding-left:10px;padding-right:10px;word-break: keep-all;background-color:white;border-style:solid;border-width:1px;border-color:lightgray;position:fixed;">
        
        <div style="width:100%;display: inline-flex;">
            <img id="_dc_message_img_" style="width:40px;height:40px;" src="">
            <a id="_dc_message_text_" style="display: inline-block;max-width: ${max_width}px;word-wrap:break-word;margin-top: 10px;margin-top: 10px;margin-bottom:30px;"></a>
        </div>
        <div style="width:100%;text-align:center;">
            <button id="_dc_ui_message_cancel_" style="display:none;border-color:gray;float:right;margin-left: 10px;">取消</button>
            <button id="_dc_ui_message_confirm_" style="display:none;float:right;margin-bottom:10px;">确定</button>
        </div>
    </div>
</div>
<div id="_dc_ui_inputor_container_" class="_dcdev_preset_" style="position:absolute;top:0px;left:0px;z-index:999999;display:none;">
    <div id="_dc_ui_inputor_container__" style="background-color: white;position: fixed;z-index:999;">
        <div id="_dc_ui_inputor_title_" class="dcdev-title" style="margin-left:10px;"></div>
        <input id="_dc_ui_inputor_char_input_" style="display:none;width:280px;height:40px;margin-left:10px;margin-bottom:0px;" type="text" oninput="_dc_ui_on_input_validate_()"/>
        <textarea id="_dc_ui_inputor_textarea_input_" style="display:none;margin-left:10px;margin-right:10px;" oninput="_dc_ui_on_input_validate_()"></textarea>
        <div id="_dc_ui_inputor_tips_" style="font-size:12px;margin-left:20px;color:gray;"></div>
        <div>
            <button id="_dc_ui_inputor_cancel_" style="border-color:gray;float:right;margin-right: 10px;">取消</button>
            <button id="_dc_ui_inputor_confirm_" style="float:right;margin-right: 10px;margin-bottom:10px;">确定</button>
        </div>
    </div>
</div>
`
        window.document.write(html);
        // 遮罩层不允许点击
        _dc_ui_block_div_events_("_dc_ui_mask_");
    }

    // loading超时器
    var _loading_timeout_;
    // loading计数器
    var _show_loadking_counter_ = [];

    ui_class = {
        // 显示loading
        show_loading: function (timeout = 5, is_mask = 1, mask_opacity = 0) {
            // 如果计数器>1,表示正在显示loading
            if (_show_loadking_counter_.length > 0) {
                // 计数器+1，表示多了一个请求
                _show_loadking_counter_.push("1");
            }
            // 表示没有显示loading,则显示
            else {
                // 是否使用遮罩
                $("#_dc_ui_mask_").css("display", is_mask ? "block" : "none").css("opacity", mask_opacity);
                $("#_dc_ui_loading_container_").css("display", "block");
            }

            // 重置超时定时器
            clearInterval(_loading_timeout_);
            _loading_timeout_ = null;
            _loading_timeout_ = setTimeout(() => {
                this.hide_loading();
            }, timeout * 1000);
        },
        // 隐藏loading
        hide_loading: function () {
            // 计数器减1
            if (_show_loadking_counter_.length > 0) {
                _show_loadking_counter_.shift();
            }
            // 计数器为0，表示需要彻底hideLoading
            if (_show_loadking_counter_.length == 0) {
                // 重置超时定时器
                clearInterval(_loading_timeout_);
                // 如果有弹出窗口，则不隐藏遮罩
                if ($("#_dc_ui_inputor_container_").css("display") != "block")
                    $("#_dc_ui_mask_").css("display", "none");
                $("#_dc_ui_loading_container_").css("display", "none");
            }
        },
        show_success: function (text, data, cb) {
            if (!data)
                data = {};
            data.type = "success";
            data.text = text;
            data.timeout = data.timeout ? data.timeout : 2;
            data.is_mask = data.is_mask ? data.is_mask : true;
            data.mask_opacity = data.mask_opacity ? data.mask_opacity : 0.8;
            data.confirm_button = data.confirm_button ? data.confirm_button : false;
            data.cb = cb;
            this._dc_show_html_(data, cb);
        },
        show_error: function (text, data, cb) {
            if (!data)
                data = {};
            data.type = "error";
            data.text = text;
            data.timeout = data.timeout ? data.timeout : 2;
            data.is_mask = data.is_mask ? data.is_mask : true;
            data.mask_opacity = data.mask_opacity ? data.mask_opacity : 0.8;
            data.confirm_button = data.confirm_button ? data.confirm_button : false;
            data.cb = cb;
            this._dc_show_html_(data, cb);
        },
        show_message: function (text, data, cb) {
            if (!data)
                data = {};
            data.type = "message";
            data.text = text;
            data.timeout = data.timeout ? data.timeout : 2;
            data.is_mask = data.is_mask ? data.is_mask : true;
            data.mask_opacity = data.mask_opacity ? data.mask_opacity : 0.8;
            data.confirm_button = data.confirm_button ? data.confirm_button : false;
            data.cb = cb;
            this._dc_show_html_(data, cb);
        },
        show_confirm: function (text, data, cb) {
            if (!data)
                data = {};
            data.type = "confirm";
            data.text = text;
            data.timeout = data.timeout ? data.timeout : 60;
            data.is_mask = data.is_mask ? data.is_mask : true;
            data.mask_opacity = data.mask_opacity ? data.mask_opacity : 0.8;
            data.cb = cb;
            this._dc_show_html_(data, cb);
        },
        show_browser: function (src, data, cb) {
            if (!data)
                data = {};
            data.type = "browser";
            data.src = src;
            data.is_mask = data.is_mask ? data.is_mask : true;
            data.mask_opacity = data.mask_opacity ? data.mask_opacity : 0.8;
            data.cb = cb;
            $.getScript("https://res.dcdev.net/dcdev/v1.0.6/assets/js/ui_browser.js", function () {
                ui_browser_class.init(data);
            })
        },
        show_inputor: function (data, cb) {
            data.is_mask = data.is_mask ? data.is_mask : true;
            data.title = data.title ? data.title : "输入";
            data.type = data.type ? data.type : "char";
            data.opacity = data.opacity ? data.opacity : 0.8;
            // 保存相关配置
            window["_dc_ui_inputor_data_"] = data;
            $(`#_dc_ui_inputor_title_`).html(data.title);
            // 是否使用遮罩
            $(`#_dc_ui_mask_`).css("display", data.is_mask ? "block" : "none").css("opacity", data.opacity).css("width", browser_info.width).css("height", browser_info.height);

            if (data.type == "char") {
                $(`#_dc_ui_inputor_textarea_input_`).css("display", "none");
                // 有默认内容
                if (data.text)
                    $("#_dc_ui_inputor_char_input_").val(data.text);
                if (browser_info.is_desktop) {
                    $(`#_dc_ui_inputor_container__`).css("width", 300).css("left", browser_info.width / 2 - 150).css("top", browser_info.height / 2 - 67);
                    $(`#_dc_ui_inputor_char_input_`).css("width", 280).css("display", "block");
                }
                else {
                    $(`#_dc_ui_inputor_container__`).css("left", 10).css("width", browser_info.width - 20).css("top", 10);
                    $(`#_dc_ui_inputor_char_input_`).css("width", browser_info.width - 40).css("display", "block");
                }
            }
            else if (data.type == "textarea") {
                $(`#_dc_ui_inputor_char_input_`).css("display", "none");
                $(`#_dc_ui_inputor_textarea_input_`).css("display", "block");
                // 有默认内容
                if (data.text)
                    $("#_dc_ui_inputor_textarea_input_").val(data.text);
                if (browser_info.is_desktop) {
                    $(`#_dc_ui_inputor_container__`).css("left", browser_info.width / 4).css("width", browser_info.width / 2).css("top", (browser_info.height - 400) / 4);
                    $(`#_dc_ui_inputor_textarea_input_`).css("width", (browser_info.width / 2 - 20)).css("height", 400);
                }
                else {
                    $(`#_dc_ui_inputor_container__`).css("left", 10).css("width", browser_info.width - 20).css("top", 10);
                    $(`#_dc_ui_inputor_textarea_input_`).css("width", (browser_info.width - 40));
                }
            }

            if (data.max_value) {
                $(`#_dc_ui_inputor_${data.type}_input_`).attr("maxlength", data.max_value);
                $(`#_dc_ui_inputor_tips_`).html(`${0} / ${data.max_value}`);
                if (data.min_value > 0) {
                    $("#_dc_ui_inputor_confirm_").attr("disabled", true);
                }
            }

            $(`#_dc_ui_inputor_${data.type}_input_`).css("display", "block");

            if (!window["_dc_ui_inputor_object_"]) {
                window["_dc_ui_inputor_object_"] = true;
                // 遮罩点击事件
                _dc_ui_block_div_events_(`_dc_ui_inputor_${data.type}_input_`);

                if (data.type == "char") {
                    // 监听输入事件
                    $(`#_dc_ui_inputor_${data.type}_input_`).keyup(function (event) {
                        var e = (event) ? event : window.event;
                        // 回车
                        if (e.keyCode == 13) {
                            // 确认按钮可用时
                            if (!($(`#_dc_ui_inputor_confirm_`).attr("disabled") == "disabled")) {
                                $(`#_dc_ui_inputor_confirm_`).click();
                            }
                        }
                        // esc 键
                        else if (e.keyCode == 27) {
                            $(`#_dc_ui_inputor_cancel_`).click();
                        }
                    });
                }

                $(`#_dc_ui_inputor_cancel_`).click(function () {
                    var data = window["_dc_ui_inputor_data_"];
                    if (cb) {
                        cb({ res: 0 });
                        $(`#_dc_ui_inputor_${data.type}_input_`).val("");
                        $(`#_dc_ui_inputor_container_`).css("display", "none");
                        $(`#_dc_ui_mask_`).css("display", "none");
                    }
                })
                $(`#_dc_ui_inputor_confirm_`).click(function () {
                    var data = window["_dc_ui_inputor_data_"];
                    if ($(`#_dc_ui_inputor_${data.type}_input_`).val() && cb) {
                        cb({ res: 1, text: $(`#_dc_ui_inputor_${data.type}_input_`).val() });
                        $(`#_dc_ui_inputor_${data.type}_input_`).val("");
                        $(`#_dc_ui_inputor_container_`).css("display", "none");
                        $(`#_dc_ui_mask_`).css("display", "none");
                    }
                })
            }
            $(`#_dc_ui_inputor_container_`).css("display", "block");
            $(`#_dc_ui_inputor_${data.type}_input_`).focus();
        },
        _dc_show_html_: function (data, cb) {
            window["_dc_ui_message_data_"] = data;
            // 是否使用遮罩
            $(`#_dc_ui_mask_`).css("display", data.is_mask ? "block" : "none").css("opacity", data.mask_opacity).css("width", browser_info.width).css("height", browser_info.height);

            if (data.type == "browser") {
                $(`#_dc_ui_container_`).append(`<iframe id="_dc_ui_browser_frame_" style="width:100%;height:100%" src='${data.url}' frameborder="0"></iframe>`);
                $(`#_dc_ui_container_`).css("left", 0);
                $(`#_dc_ui_container_`).css("top", 0);
                $(`#_dc_ui_container_`).css("width", 500);
                $(`#_dc_ui_container_`).css("height", 500);
                $(`#_dc_ui_container_`).css("display", "block");
                $(`body`).append(`<div id="_dc_forbidden_mask_" style="position:fixed;left:0px;top:0px;width:500px;height:500px;"></div>`)
                // 遮罩层不允许点击
                _dc_ui_block_div_events_("_dc_forbidden_mask_");
            }
            else {
                if (data.type == "confirm") {
                    $(`#_dc_message_img_`).attr("src", `https://res.dcdev.net/dcdev/v1.0.6/assets/images/message.svg`);
                }
                else {
                    $(`#_dc_message_img_`).attr("src", `https://res.dcdev.net/dcdev/v1.0.6/assets/images/${data.type}.svg`);
                }
                document.getElementById(`_dc_message_text_`).innerHTML = data.text;
                $(`#_dc_ui_container_`).css("left", -500);
                $(`#_dc_ui_container_`).css("top", -500);
                $(`#_dc_ui_container_`).css("display", "block");
                // 计算宽高
                var width = document.getElementById("_dc_ui_container__").clientWidth + 2;
                var height = document.getElementById("_dc_ui_container__").clientHeight + 2;
                if (data.confirm_button) {
                    $(`#_dc_ui_message_confirm_`).css("display", "block");
                }

                if (data.type == "confirm") {
                    $(`#_dc_ui_message_confirm_`).css("display", "block");
                    $(`#_dc_ui_message_cancel_`).css("display", "block");
                }
                var offset = browser_info.is_wechat ? 40 : 0;
                $(`#_dc_ui_container__`).css("left", browser_info.width / 2 - width / 2).css("top", browser_info.height / 2 - height / 2 - offset);

                // 未初始化相关事件
                if (!window["_dc_ui_message_object_"]) {
                    window["_dc_ui_message_object_"] = true;
                    $("#_dc_ui_message_confirm_").click(function () {
                        var data = window["_dc_ui_message_data_"];
                        clearTimeout(data._timeout);
                        if (data.cb) {
                            $(`#_dc_ui_container_`).css("display", "none");
                            $(`#_dc_ui_mask_`).css("display", "none");
                            $(`#_dc_ui_message_confirm_`).css("display", "none");
                            $(`#_dc_ui_message_cancel_`).css("display", "none");
                            data.cb({
                                res: 1,
                            });
                        }
                    })
                    $("#_dc_ui_message_cancel_").click(function () {
                        var data = window["_dc_ui_message_data_"];
                        clearTimeout(data._timeout);
                        if (data.cb) {
                            $(`#_dc_ui_container_`).css("display", "none");
                            $(`#_dc_ui_mask_`).css("display", "none");
                            $(`#_dc_ui_message_confirm_`).css("display", "none");
                            $(`#_dc_ui_message_cancel_`).css("display", "none");
                            data.cb({
                                res: 0,
                            });
                        }
                    })
                }

                if (!data._timeout) {
                    // 隐藏函数
                    data._timeout = setTimeout(() => {
                        $("#_dc_ui_mask_").css("display", "none");
                        $("#_dc_ui_container_").css("display", "none");
                    }, data.timeout * 1000);
                }
            }
        },
    }
})(window);
